#!/usr/bin/perl
# This is a sample script for interfacing with ArDAS.

use FileHandle;
use Time::HiRes qw(usleep);
use POSIX qw(strftime);

open(SER, "+>/dev/ttyUSB0") or die "Cannot open serial port: $!\n";
SER->autoflush(1);

die "Logfile 'data.log' already exists, will not overwrite" if -e 'data.log';

open(DATA, ">data.log");
DATA->autoflush(1);


print SER "sensor ds18x20 init 6\n";
print SER "sensor ds18x20 init 7\n";

my $i == 0;
my ($rh0, $rh1, $t0, $t1) = (0,0,0,0);

while(1) {
	# First sample RH and T
	my $t = time();
	my $tstr = strftime "%H:%M:%S", localtime($t);

	if($i & 1) {
		print SER "sensor shtxx srh 2 3\n";
		print SER "sensor shtxx srh 4 5\n";
	} else {
		print SER "sensor shtxx st 2 3\n";
		print SER "sensor shtxx st 4 5\n";
	}

	print SER "sensor ds18x20 sample 6\n";
	print SER "sensor ds18x20 sample 7\n";
	sleep(1);
	# Wait a sec and read data
	print SER "sensor shtxx read 2 3\n";
	usleep(50000); # 50ms wait;
	print SER "sensor shtxx read 4 5\n";
	usleep(50000);
	print SER "sensor ds18x20 read 6\n";
	usleep(50000);
	print SER "sensor ds18x20 read 7\n";
	usleep(50000);

	@data = <SER>;
	foreach(@data) {
		next unless(/(\w+)\[(.+?)\]:\s+(\d+)/);
	
		if(lc($1) eq 'shtxx') {
			if($i & 1) {
				$rh0 = $3 if $2 eq 'sda:2, scl:3';
				$rh1 = $3 if $2 eq 'sda:4, scl:5';
			} else {
				$t0 = $3 if $2 eq 'sda:2, scl:3';
				$t1 = $3 if $2 eq 'sda:4, scl:5';
			}
		} elsif(lc($1) eq 'ds18x20') {
			$t2 = $3 if $2 eq '6';
			$t3 = $3 if $2 eq '7';
		}
	}

	print "$tstr T0=$t0 T1=$t1 T2=$t2 T3=$t3 RH0=$rh0 RH1=$rh1\n";
	print DATA "$t $t0 $t1 $t2 $t3 $rh0 $rh1\n";

	sleep(10) if($i++ & 1);
}

